﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Summary description for Common
/// </summary>
public class Common : System.Web.UI.Page
{
    public Common()
    {
        //
        // TODO: Add constructor logic here
        //
    }



    public string q(string s)
    {
        if (Request.QueryString[s] != null)
        {
            return Request.QueryString[s].ToString();
        }
        return string.Empty;
    }

    /// <summary>
    /// 获取post得到的参数
    /// </summary>
    /// <param name="s">参数名</param>
    /// <returns>返回值</returns>
    public string f(string s)
    {
        if (Request.Form[s] == null) return string.Empty;
        return Request.Form[s];
    }


    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径（物理路径）</param>
    /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>    
    public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW"://指定高宽缩放（可能变形）                
                break;
            case "W"://指定宽，高按比例                    
                if (width < ow)
                    toheight = originalImage.Height * width / originalImage.Width;
                else
                {
                    towidth = ow;
                    toheight = oh;
                }
                break;
            case "H"://指定高，宽按比例
                if (height < oh)
                    towidth = originalImage.Width * height / originalImage.Height;
                else
                {
                    towidth = ow;
                    toheight = oh;
                }
                break;
            case "Cut"://指定高宽裁减（不变形）                
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }

    /// <summary>
    /// 修改XML
    /// </summary>
    /**
    <data>
        <channel>
            <item>
	            <link>http://www.pfdc1977.com</link>
	            <image>images/image1.jpg</image>
	            <title>Bell Tower,Xi'an,China</title>
            </item>
        </channel>
        <config>	
            ......
        </config>
    </data>
    **/
    public void ModifyXML()
    {
        int limit = 5;
        string sql = "select pcid, pcname, pccoverpicture, ipindex from PictureCategory, IndexPicture where pcid = ipid order by ipindex desc limit " + limit;
        DataSet ds = DBFunctions.GetDataSetDB(sql);
        while (ds.Tables[0].Rows.Count < 1)
        {
            ds.Tables[0].Rows.Add(-1, "暂时空缺","images/nopic.gif", 0);
        }

        string xmlFilePath = this.Server.MapPath("~/upload/bcastr.xml"); //Xml 文件路路
        XmlDocument xmlDoc = new XmlDocument(); //创建对象
        xmlDoc.Load(xmlFilePath);
        XmlNodeList rootList = xmlDoc.SelectSingleNode("data").ChildNodes; //获取节点下的子节点列表
        XmlNodeList channelList = xmlDoc.SelectSingleNode("data").SelectSingleNode("channel").ChildNodes;
        XmlNode channelNode = xmlDoc.SelectSingleNode("data").SelectSingleNode("channel");

        channelNode.RemoveAll();
        /**
        int j = channelList.Count;
        while (--j > -1)
        {
            XmlElement xe = (XmlElement)channelList[j];
            xe.ParentNode.RemoveChild(xe);
        }**/
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            XmlNode itemNode = xmlDoc.CreateNode(XmlNodeType.Element, "item", ""); //新建节点
            XmlNode linkNode = xmlDoc.CreateNode(XmlNodeType.Element, "link", ""); //新建节点
            linkNode.InnerText = "Pictures.aspx?pcid=" + ds.Tables[0].Rows[i]["pcid"];
            XmlNode imageNode = xmlDoc.CreateNode(XmlNodeType.Element, "image", ""); //新建节点
            imageNode.InnerText = ds.Tables[0].Rows[i]["pccoverpicture"].ToString();
            XmlNode titleNode = xmlDoc.CreateNode(XmlNodeType.Element, "title", ""); //新建节点
            titleNode.InnerText = ds.Tables[0].Rows[i]["pcname"].ToString();
            itemNode.AppendChild(linkNode);
            itemNode.AppendChild(imageNode);
            itemNode.AppendChild(titleNode);
            channelNode.AppendChild(itemNode);
        }
        xmlDoc.Save(xmlFilePath);
    }

    public bool CheckExtension(string ext, string[]targetExt)
    {
        for (int i = 0; i < targetExt.Length; i++)
        {
            if (targetExt[i].ToLower() == ext.ToLower()) { return true; }
        }
        return false;
    }

    public bool CheckExtension(string ext)
    {
        string[] targetExt = { "jpg", "jpeg", "bmp", "gif", "png" };
        for (int i = 0; i < targetExt.Length; i++)
        {
            if (targetExt[i].ToLower() == ext.ToLower()) { return true; }
        }
        return false;
    }
}